package cn.com.joycode.nimble.core.message;

import cn.com.joycode.nimble.core.utils.ObjectMapperUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author Max Woods
 */

@Slf4j
public class NbMsgSign {

    private static final SignAlgorithm SIGN_ALGORITHM = SignAlgorithm.SHA1withRSA;

    private Sign sign;

    public NbMsgSign(String privateKey, String publicKey) {
        sign = new Sign(SIGN_ALGORITHM, privateKey, publicKey);
    }

    public NbMsgSign(PrivateKey privateKey, PublicKey publicKey) {
        sign = new Sign(SIGN_ALGORITHM, privateKey, publicKey);
    }

    public void sign(NbMsg nbMsg) {
        log.info("{}", nbMsg);
        byte[] data = nbMsg.toBytes();
        log.info("{}", data);
        byte[] signature = sign.sign(data);
        nbMsg.getHeader().setSignature(Base64.encode(signature));
    }

    public boolean verify(NbMsg nbMsg) {
        byte[] signature = Base64.decode(nbMsg.getHeader().getSignature());
        NbMsg clone = ObjectMapperUtil.parseObject(nbMsg.toString(), NbMsg.class);
        clone.getHeader().setSignature(null);
        byte[] data = clone.toBytes();
        return sign.verify(data, signature);
    }
}
